package com.xywy.common.util;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.widget.PopupWindow;

/**
 * 名称: CalendarUtil
 * 描述:日历、时间处理类
 * @author xgd
 */
public class CalendarUtil {

    private static final SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final SimpleDateFormat timeFormat2 = new SimpleDateFormat("yyyy-MM-dd");
    private static final SimpleDateFormat timeFormat3 = new SimpleDateFormat("yyyy.MM.dd");

    private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>() {
        @Override
        protected DateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd");
        }
    };

    /**
     * 取得当月月份(1,2,3...10,11,12)
     *
     * @return int
     * @version1.0
     */
    public static String getCurMonth() {
        Calendar cal = Calendar.getInstance();
        return String.valueOf(cal.get(Calendar.MONTH) + 1);
    }

    /**
     * 取得当月的上个月(1,2,3...10,11,12),若当月是1月上月则是12月
     *
     * @return int
     * @version1.0
     */
    public static int getLastMonth() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 1);
        return cal.get(Calendar.MONTH) + 1;
    }

    /**
     * 取得当月的上个月所在的年份
     *
     * @return int
     * @version1.0
     */
    public static int getYearByMonth() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 1);
        return cal.get(Calendar.YEAR);
    }

    /**
     * 取得当前年份（4位数字表示）
     *
     * @return String
     * @version1.0
     */

    public static String getCurrentYear() {
        Calendar cal = Calendar.getInstance();
        return String.valueOf(cal.get(Calendar.YEAR));
    }

    /**
     * 取得时间所在年份（4位数字表示）
     *
     * @return String
     * @version1.0
     */
    public static String getCurrentYear(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return String.valueOf(cal.get(Calendar.YEAR));
    }

    /**
     * 取得当前是全年的第几周
     *
     * @return int
     * @version1.0
     */
    public static int getCurrentWeek() {
        Calendar cal = Calendar.getInstance();
        cal.setFirstDayOfWeek(Calendar.MONDAY); // 设置一周从星期一开始
        return cal.get(Calendar.WEEK_OF_YEAR);
    }

    /**
     * 根据年份和某周取得某周的最后一天（星期日），若该周是该年的最后一周，返回yyyy-12-31
     *
     * @param yearStr 年份 格式是yyyy
     * @param weekStr 第几周
     * @return String 格式:yyyy-MM-dd
     * @version1.0
     */
    public static String getLastDayByWeek(String yearStr, String weekStr) {
        int year = Integer.parseInt(yearStr);
        int week = Integer.parseInt(weekStr);
        Calendar cal = Calendar.getInstance();
        cal.setFirstDayOfWeek(Calendar.MONDAY); // 设置一周从星期一开始
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.WEEK_OF_YEAR, week);
        cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); // 假设时间是这周的星期天
        int day = cal.get(Calendar.DATE);
        int month = cal.get(Calendar.MONTH) + 1;
        if (month == 1 && week > 6) {
            return year + "-12-31";
        }
        return year + "-" + month + "-" + day;
    }

    /**
     * 取得当月的最后一天
     */
    public static String getLastDayInCurMonth() {
        Calendar cal = Calendar.getInstance();
        return String.valueOf(cal.getActualMaximum(Calendar.DAY_OF_MONTH));
    }

    /**
     * 取得某年某月的最后一天
     *
     * @param year
     * @param month
     * @return
     */
    public static String getLastDay(String year, String month) throws Exception {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, Integer.parseInt(year));
        cal.set(Calendar.MONTH, Integer.parseInt(month) - 1);
        cal.set(Calendar.DATE, 1);
        return String.valueOf(cal.getActualMaximum(Calendar.DAY_OF_MONTH));
    }

    /**
     * 取得某年2月的最后一天
     */
    public static String getLastDayForFeb(int year) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, 1);
        cal.set(Calendar.DATE, 1);
        return String.valueOf(cal.getActualMaximum(Calendar.DAY_OF_MONTH));
    }

    /**
     * 根据年份和某周取得某周的最后一天（星期日），若该周是该年的第一周，返回yyyy-1-1
     *
     * @param yearStr 年份 格式是yyyy
     * @param weekStr 第几周
     * @return String 格式:yyyy-MM-dd
     * @version1.0
     */
    public static String getFirstDayByWeek(String yearStr, String weekStr) {
        int year = Integer.parseInt(yearStr);
        int week = Integer.parseInt(weekStr);
        Calendar cal = Calendar.getInstance();
        cal.setFirstDayOfWeek(Calendar.MONDAY); // 设置一周从星期一开始
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.WEEK_OF_YEAR, week);
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); // 假设这周的星期一
        int day = cal.get(Calendar.DATE);
        int month = cal.get(Calendar.MONTH) + 1;
        if (month != 1 && week == 1) {
            return year + "-1-1";
        }
        return year + "-" + month + "-" + day;
    }

    /**
     * 根据日期（yyyy-MM-dd)取得日期是该年的第几周
     *
     * @param year  yyyy
     * @param month mm
     * @param day   dd
     * @return String
     * @version1.0
     */
    public static String getWeekByDate(String year, String month, String day) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, Integer.parseInt(year));
        cal.set(Calendar.MONTH, Integer.parseInt(month) - 1);
        cal.set(Calendar.DATE, Integer.parseInt(day));
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        return String.valueOf(cal.get(Calendar.WEEK_OF_YEAR));
    }

    /**
     * 根据日期（yyyy-MM-dd)取得日期是该年的第几周
     *
     * @param date
     * @return String
     * @version1.0
     */
    public static String getWeekByDate(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        return String.valueOf(cal.get(Calendar.WEEK_OF_YEAR));
    }

    /**
     * 将日期转换成MM月dd日
     *
     * @param date yyyy-MM-dd
     * @return String
     * @version1.0
     */
    public static String toChinaDate(String date) {
        String[] dateArr = date.split("-");
        return dateArr[0] + "年" + dateArr[1] + "月" + dateArr[2] + "日";
    }

    /**
     * 转换日期格式 返回的格式是yyyy-MM-dd HH:mm:ss
     *
     * @param date Date类型
     * @return String
     */

    public static String convertToYYYYMMDDHHMMSS(Date date) {
//        SimpleDateFormat timeFormat3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return timeFormat.format(date);
    }


    /**
     * 转换日期格式 返回的格式是yyyy-MM-dd
     *
     * @param date Date类型
     * @return String
     */

    public static String convertToYYYYMMDD(Date date) {
        if (date == null) {
            return "";
        }
        return timeFormat2.format(date);
    }

    /**
     * 转换日期格式 返回的格式是yyyy.MM.dd
     *
     * @param date Date类型
     * @return String
     */

    public static String convertToYYYYMMDD2(Date date) {
        if (date == null) {
            return "";
        }
        return timeFormat3.format(date);
    }

    public static Date string2DateThread(String dStr) {
        try {
            return df.get().parse(dStr);
        } catch (Exception e) {
            // logger.error("日期转换异常",e);
            return null;
        }
    }

    /**
     * 将yyyy-MM-dd HH:mm:ss格式的字符串转换为Date对象
     *
     * @param dStr
     * @return
     * @throws Exception
     */
    public static Date string2Time(String dStr) {
        try {
            return timeFormat.parse(dStr);
        } catch (Exception e) {
            // logger.error("日期转换异常",e);
            return null;
        }
    }

    /**
     * 返回strDate2和strDate1相差的天数，若strDate1 比strDate2 大则返回负数,相等返回0
     *
     * @param strDate1 yyyy-MM-dd
     * @param strDate2 yyyy-MM-dd
     * @return
     * @throws Exception
     */
    public static int compareDateThread(String strDate1, String strDate2) {
        int compareDate = 0;
        try {
            Date date1 = df.get().parse(strDate1);
            Date date2 = df.get().parse(strDate2);
            long rel = date2.getTime() - date1.getTime();
            compareDate = (int) (rel / (1000 * 60 * 60 * 24));
        } catch (Exception e) {
            // logger.error("返回相差的天数异常",e);
        }
        return compareDate;
    }

    /**
     * 返回strDate2和strDate1相差的天数，若strDate1 比strDate2 大则返回负数,相等返回0
     *
     * @param strDate1 yyyy-MM-dd
     * @param strDate2 yyyy-MM-dd
     * @return
     * @throws Exception
     */
    public static int compareDate(Date strDate1, Date strDate2) {
        int compareDate = 0;
        try {
            long rel = strDate2.getTime() - strDate1.getTime();
            compareDate = (int) (rel / (1000 * 60 * 60 * 24));
        } catch (Exception e) {
            // logger.error("返回相差的天数异常",e);
        }
        return compareDate;
    }

    /**
     * 返回strTime2和strTime1相差的小时数，若strTime1 比strTime2 大则返回负数
     *
     * @param strTime1 yyyy-MM-dd HH:mm:ss
     * @param strTime2 yyyy-MM-dd HH:mm:ss
     * @return
     * @throws Exception
     */
    public static long compareHour(String strTime1, String strTime2) {
        long compareHour = 0L;
        try {
            Date date1 = timeFormat.parse(strTime1);
            Date date2 = timeFormat.parse(strTime2);
            Long rel = date2.getTime() - date1.getTime();
            compareHour = rel / (1000 * 60 * 60);
        } catch (Exception e) {
            // logger.error("返回相差的小时数异常",e);
        }
        return compareHour;
    }

    public static long compareMinute(Date date1, Date date2) {
        long rel = date2.getTime() - date1.getTime();
        return rel / (1000 * 60);
    }

    /**
     * 加时间后得到日期
     */
    public static Date addTime(Date date, long time) {
        if (date == null) {
            return new Date();
        }
        Date newDate = new Date(date.getTime() + time);
        return newDate;
    }

    /**
     * 减时间后得到日期
     */
    public static Date subtructTime(Date date, long time) {
        if (date == null) {
            return new Date();
        }
        Date newDate = new Date(date.getTime() - time);
        return newDate;
    }

    /**
     * 拆分日期，封装到String数组
     *
     * @param date
     * @return
     * @throws Exception
     */
    public static String[] splitDate(Date date) {
        String[] retArr = new String[6];
        String strDate = convertToYYYYMMDDHHMMSS(date);
        String[] strArr1 = strDate.split(" ");
        String[] strArr2 = strArr1[0].split("-");
        String[] strArr3 = strArr1[1].split(":");
        retArr[0] = strArr2[0];
        retArr[1] = strArr2[1];
        retArr[2] = strArr2[2];

        retArr[3] = strArr3[0];
        retArr[4] = strArr3[1];
        retArr[5] = strArr3[2];

        return retArr;
    }

    /**
     * 获取指定日期的后一天
     *
     * @param today
     * @return
     */
    public static String getNextDayThread(String today) {
        // logger.info("getNextDayThread.today:{}",today);
        String nextDay = "";
        try {
            Calendar c = Calendar.getInstance();
            c.setTime(CalendarUtil.string2DateThread(today));
            int day = c.get(Calendar.DATE);
            c.set(Calendar.DATE, day + 1);

            nextDay = df.get().format(c.getTime());
        } catch (Exception e) {
            // logger.error("获取指定日期的后一天异常",e);
        }
        return nextDay;
    }

    /**
     * 获取指定日期的下一周
     *
     * @param today
     * @return
     */
    public static String getNextWeekThread(String today) {
        // logger.info("getNextWeekThread.today:{}",today);
        String nextWeek = "";
        try {
            Calendar c = Calendar.getInstance();
            c.setTime(CalendarUtil.string2DateThread(today));
            int week = c.get(Calendar.WEEK_OF_YEAR);
            c.set(Calendar.WEEK_OF_YEAR, week + 1);

            nextWeek = df.get().format(c.getTime());
        } catch (Exception e) {
            // logger.error("获取指定日期的下一周异常",e);
        }
        return nextWeek;
    }

    public static String getNextMonthThread(String today) {
        // logger.info("getNextMonthThread.today:{}",today);

        String nexMonth = "";
        try {
            Calendar c = Calendar.getInstance();
            c.setTime(CalendarUtil.string2DateThread(today));
            int month = c.get(Calendar.MONTH);
            c.set(Calendar.MONTH, month + 1);

            nexMonth = df.get().format(c.getTime());
        } catch (Exception e) {
            // logger.error("获取指定日期下一月异常",e);
        }

        return nexMonth;
    }

    /**
     * 增加或减少年后的日期
     *
     * @param today
     * @return
     */
    public static String getNextYearThread(String today) {
        // logger.info("getNextYearThread.today:{}",today);

        String yearAfter = "";
        try {
            Calendar c = Calendar.getInstance();
            c.setTime(CalendarUtil.string2DateThread(today));
            int year = c.get(Calendar.YEAR);
            c.set(Calendar.YEAR, year + 1);

            yearAfter = df.get().format(c.getTime());
        } catch (Exception e) {
            // logger.error("获取增加或减少年后的日期异常",e);
        }
        return yearAfter;
    }

    /**
     * 对 时间戳进行转换
     *
     * @param timestamp
     * @return
     */
    public static String convertToTimestamp(Timestamp timestamp) {
        return timeFormat.format(timestamp);
    }

    /**
     * 将时间戳转为代表"距现在多久之前"的字符串
     * @param timeStr   时间戳
     * @return
     */
    public static String getStandardDate(long timeStr) {

        StringBuffer sb = new StringBuffer();

        //long t = Long.parseLong(timeStr);
        long time = System.currentTimeMillis() - (timeStr*1000);
        long mill = (long) Math.ceil(time /1000);//秒前

        long minute = (long) Math.ceil(time/60/1000.0f);// 分钟前

        long hour = (long) Math.ceil(time/60/60/1000.0f);// 小时

        long day = (long) Math.ceil(time/24/60/60/1000.0f);// 天前

        if (day - 1 > 0) {
            sb.append(day + "天");
        } else if (hour - 1 > 0) {
            if (hour >= 24) {
                sb.append("1天");
            } else {
                sb.append(hour + "小时");
            }
        } else if (minute - 1 > 0) {
            if (minute == 60) {
                sb.append("1小时");
            } else {
                sb.append(minute + "分钟");
            }
        } else if (mill - 1 > 0) {
            if (mill == 60) {
                sb.append("1分钟");
            } else {
                sb.append(mill + "秒");
            }
        } else {
            sb.append("刚刚");
        }
        if (!sb.toString().equals("刚刚")) {
            sb.append("前");
        }
        return sb.toString();
    }

    /**
     * 时间戳转为时间
     * @param time
     * @return
     */
    public static String getStrTime(String time) {
        String re_StrTime = null;
        SimpleDateFormat sdf = null;
        if (time.equals("")) {
            return "";
        }
        sdf = new SimpleDateFormat("HH:mm");
        long loc_time = Long.valueOf(time);
        re_StrTime = sdf.format(new Date(loc_time * 1000L));
        return re_StrTime;
    }
    /**
     * 时间戳转为时间
     * @param time
     * @return
     */
    public static String getStrTime2(String time) {
        String re_StrTime = null;
        SimpleDateFormat sdf = null;
        if (time.equals("")) {
            return "";
        }
        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        long loc_time = Long.valueOf(time);
        re_StrTime = sdf.format(new Date(loc_time * 1000L));
        return re_StrTime;
    }
    /**
     *    将字符串转为时间戳
     */
    public static String getTimstamp(String user_time) {
        String re_time = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date d;
        try {
            d = sdf.parse(user_time);
            long l = d.getTime();
            String str = String.valueOf(l);
            re_time = str.substring(0, 9);
//            re_time = re_time;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println("将字符串转为时间戳:"+re_time);
        return re_time;
    }

    /**
     * 　　 * 获取当前月度字符串。
     * 　　 * 日期字符串格式： dd
     *
     */
    public static Integer getNowDay() {
        SimpleDateFormat formatter = new SimpleDateFormat("dd");
        String forDay = formatter.format(new Date());
        return new Integer(forDay);
    }

    /**
     * 获取现在时间
     *
     * @return返回字符串格式 yyyy-MM-dd HH:mm:ss
     */
    public static String getYYYYMMddDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    /**
     * 两个时间之间相差距离多少天
     *
     * @param str1 时间参数 1：
     * @param str2 时间参数 2：
     * @return 相差天数
     */
    public static long getDistanceDays(String str1, String str2) throws Exception {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date one;
        Date two;
        long days = 0;
        try {
            one = df.parse(str1);
            two = df.parse(str2);
            long time1 = one.getTime();
            long time2 = two.getTime();
            long diff;
            if (time1 < time2) {
                diff = time2 - time1;
            } else {
                diff = time1 - time2;
            }
            days = diff / (1000 * 60 * 60 * 24);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return days;
    }


    public static void main(String[] args) {
        String str1 = "2014-01-14";
        String str2 = "2014-01-15";
        try {
            System.out.println(getDistanceDays(str1, str2));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static final long YEAR = 365;
	public static final long MONTH = 30;
	public static final long DAY = 24;
	public static final long HOUR = 60;
	public static final long MINUTE = 60;
	public static final long SECOND = 1000;
	static long timeFormate[] = new long[6];
	static String timeFormateStr[] = { "年前", "个月前", "天前", "小时前", "分钟前", "秒前" };

	public static String getDiffTime(long dataTime) {
		long currentTime = System.currentTimeMillis();
		long diff = currentTime - dataTime;
		timeFormate[0] = diff / (YEAR * MONTH * DAY * HOUR * MINUTE * SECOND);
		timeFormate[1] = diff / (MONTH * DAY * HOUR * MINUTE * SECOND);
		timeFormate[2] = diff / (DAY * HOUR * MINUTE * SECOND);
		timeFormate[3] = diff / (HOUR * MINUTE * SECOND);
		timeFormate[4] = diff / (MINUTE * SECOND);
		timeFormate[5] = diff / (SECOND);
		int i = 0;
		for (; i < timeFormate.length; i++) {
			if (timeFormate[i] != 0)
				break;
		}
		if (i >= 5) {
			return "刚刚";
		}
		return timeFormate[i] + timeFormateStr[i];
	}

}
